package com.bawei.module_mine

import android.content.Intent
import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.launcher.ARouter

import com.bawei.lib_common.mvi.base.BaseMVIFragment
import com.bawei.lib_common.aop.LoginInterceptor
import com.bawei.lib_common.aop.LoginManager
import com.bawei.lib_common.utils.UserUtils
import com.bawei.lib_common.utils.HistoryDebugUtils
import com.bawei.lib_common.utils.ScrollConflictUtils
import com.bawei.lib_storage.room.HistoryManager
import com.bawei.lib_storage.room.FavoriteManager
import com.bawei.module_mine.adapter.HistoryAdapter
import com.bawei.module_mine.adapter.FavoriteAdapter
import com.bawei.module_mine.adapter.OfflineCacheAdapter
import com.bawei.module_mine.databinding.FragmentMineBinding
import com.bawei.module_mine.ui.LoginActivity
import com.bawei.module_mine.ui.OpenLiveActivity
import com.bawei.module_mine.ui.WithdrawActivity
import kotlinx.coroutines.launch
import kotlin.math.log
import android.content.Context
import androidx.appcompat.app.AppCompatDelegate
import com.bumptech.glide.Glide
import android.Manifest
import android.app.Activity
import android.content.ContentValues
import android.graphics.Bitmap
import android.graphics.ImageDecoder
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.provider.MediaStore
import android.widget.TextView
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import com.bawei.module_mine.utils.AvatarUtils
import com.google.android.material.bottomsheet.BottomSheetDialog
import java.io.File
import java.io.IOException
import com.bawei.module_mine.ui.CameraActivity
import androidx.core.content.FileProvider


class MineFragment : BaseMVIFragment() {
    private var _binding: FragmentMineBinding? = null
    private val binding get() = _binding!!
    
    private lateinit var historyAdapter: HistoryAdapter
    private lateinit var favoriteAdapter: FavoriteAdapter
    private lateinit var offlineCacheAdapter: OfflineCacheAdapter
    
    // 添加成员变量用于记录触摸起始点
    private var startX = 0f
    private var startY = 0f
    
    private lateinit var pickImageLauncher: ActivityResultLauncher<Intent>
    private lateinit var cameraLauncher: ActivityResultLauncher<Intent>
    private lateinit var requestPermissionLauncher: ActivityResultLauncher<Array<String>>
    
    // 用于缓存待显示的金币数
    private var pendingCoinAmount: Double? = null
    
    override fun initView() {
        super.initView()
        Log.d("MineFragment", "initView called")
        
        // 初始化历史记录适配器
        initHistoryAdapter()
        
        // 初始化收藏适配器
        initFavoriteAdapter()
        
        // 初始化离线缓存适配器
        initOfflineCacheAdapter()
        
        // 设置点击事件
        setupClickListeners()

        // 深色模式开关逻辑
        val sp = requireContext().getSharedPreferences("settings", Context.MODE_PRIVATE)
        val isDark = sp.getBoolean("dark_mode", false)
        binding.switchDarkMode.isChecked = isDark
        binding.switchDarkMode.setOnCheckedChangeListener { _, checked ->
            sp.edit().putBoolean("dark_mode", checked).apply()
            if (checked) {
                AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES)
            } else {
                AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO)
            }
            activity?.recreate()
        }
    }
    
    /**
     * 设置点击事件
     */
    private fun setupClickListeners() {
        // 设置发布动态点击事件
        binding.tvMinePublishDynamic.setOnClickListener {
            showMsg("跳转到发布动态页面")
        }
        
        // 设置发视频点击事件
        binding.tvMinePublishtake.setOnClickListener {
            showMsg("跳转到发视频页面")
        }
        
        // 设置历史记录全部按钮点击事件
        binding.tvMineHistoryAll.setOnClickListener {
            // 跳转到历史记录页面
            ARouter.getInstance().build("/module_mine/TestHistoryActivity").navigation()
        }
        
        // 设置离线缓存点击事件
        binding.mineTextview2.setOnClickListener {
            showMsg("跳转到离线缓存页面")
        }
        
        // 设置我的收藏点击事件
        binding.mineTextview3.setOnClickListener {
            // 跳转到收藏页面
            try {
                ARouter.getInstance().build("/module_mine/StoreActivity").navigation()
            } catch (e: Exception) {
                Log.e("MineFragment", "跳转到收藏页面失败: ${e.message}", e)
                showMsg("跳转失败")
            }
        }
        
        // 设置开直播点击事件
        binding.tvMineLive.setOnClickListener {
            try {
                //ARouter.getInstance().build("/module_mine/KaizhiboActivity").navigation()
                ARouter.getInstance().build("/module_mine/TengxunActivity").navigation()

                // ARouter.getInstance().build("/module_mine/OpenLiveActivity").navigation()
            } catch (e: Exception) {
                Log.e("MineFragment", "跳转到开直播页面失败: ${e.message}", e)
                showMsg("跳转失败")
            }
        }
        
        // 设置提现点击事件
        binding.viewMineInfoTitleview.tvMineInfoWithdraw.setOnClickListener {
            try {
                ARouter.getInstance().build("/module_mine/WithdrawActivity").navigation()
            } catch (e: Exception) {
                Log.e("MineFragment", "跳转到提现页面失败: ${e.message}", e)
                showMsg("跳转失败")
            }
        }
        
        // 设置个人主页点击事件
        binding.viewMineInfoTitleview.tvMineInfoMain.setOnClickListener {
             try {
                 ARouter.getInstance().build("/module_mine/ProfileActivity").navigation()
             } catch (e: Exception) {
                 Log.e("MineFragment", "跳转到个人主页失败: ${e.message}", e)
                 showMsg("跳转失败")
             }
        }
        
        // 设置我的服务全部点击事件
        binding.tvAllServices.setOnClickListener {
            showMsg("跳转到我的服务页面")
        }
        
        // 设置购物车点击事件
        binding.tvShoppingCart.setOnClickListener {
            showMsg("跳转到购物车页面")
            ARouter.getInstance()
                .build("/module_goods/GoodsActivity")
                .navigation()
        }
        
        // 设置订单点击事件
        binding.tvOrder.setOnClickListener {
            showMsg("跳转到订单页面")
        }
        
        // 设置钱包点击事件，跳转到足迹页面
        binding.tvWallet.setOnClickListener {
            val intent = Intent(requireContext(), com.bawei.module_goods.ui.FootPrintActivity::class.java)
            startActivity(intent)
        }
        
        // 设置设置点击事件
        binding.tvSettings.setOnClickListener {
            val intent = android.content.Intent(requireContext(), com.bawei.module_mine.ui.AddressListActivity::class.java)
            startActivity(intent)
        }
        
        // 设置用户名点击事件 - 跳转到一键登录
        binding.viewMineInfoTitleview.tvMineInfoUsername.setOnClickListener {
            try {
                // 使用LoginManager管理跳转，防止重复页面
                val jumped = LoginManager.navigateToQuickLogin(requireContext())
                if (!jumped) {
                    Log.d("MineFragment", "跳转被阻止，可能登录页面已显示或跳转过于频繁")
                }
            } catch (e: Exception) {
                Log.e("MineFragment", "跳转到一键登录失败: ${e.message}", e)
                showMsg("跳转失败")
            }
        }

        initAvatarPick()
        binding.viewMineInfoTitleview.ivMineInfoHeaderimg.setOnClickListener {
            showAvatarPickDialog()
        }
    }
    
    /**
     * 初始化历史记录适配器
     */
    private fun initHistoryAdapter() {
        historyAdapter = HistoryAdapter()
        
        // 设置历史记录点击事件
        historyAdapter.onItemClickListener = { historyEntity ->
            navigateToVideoDetail(historyEntity)
        }
        
        // 设置横向布局 - 修复：绑定到正确的历史记录RecyclerView
        binding.rvMineHistory.apply {
            adapter = historyAdapter
            layoutManager = LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false)
            
            // 简单的滑动冲突解决方案
            setOnTouchListener { _, event ->
                when (event.action) {
                    android.view.MotionEvent.ACTION_DOWN -> {
                        Log.d("MineFragment", "历史记录触摸开始")
                    }
                    android.view.MotionEvent.ACTION_MOVE -> {
                        // 直接阻止父容器拦截所有触摸事件
                        parent?.requestDisallowInterceptTouchEvent(true)
                        Log.d("MineFragment", "历史记录触摸移动，阻止父容器拦截")
                    }
                    android.view.MotionEvent.ACTION_UP, android.view.MotionEvent.ACTION_CANCEL -> {
                        // 恢复父容器的触摸拦截
                        parent?.requestDisallowInterceptTouchEvent(false)
                        Log.d("MineFragment", "历史记录触摸结束，恢复父容器拦截")
                    }
                }
                false // 返回false，让RecyclerView继续处理触摸事件
            }
        }
        
        // 加载历史记录数据
        loadHistoryData()
    }
    
    /**
     * 初始化收藏适配器
     */
    private fun initFavoriteAdapter() {
        favoriteAdapter = FavoriteAdapter()
        
        // 设置收藏点击事件
        favoriteAdapter.onItemClickListener = { favoriteEntity ->
            navigateToVideoDetail(favoriteEntity)
        }
        
        // 设置收藏取消收藏事件
        favoriteAdapter.onUnfavoriteClickListener = { favoriteEntity ->
            unfavoriteVideo(favoriteEntity)
        }
        
        // 设置横向布局
        binding.rvMineSc.apply {
            adapter = favoriteAdapter
            layoutManager = LinearLayoutManager(requireActivity(), LinearLayoutManager.HORIZONTAL, false)
            
            // 简单的滑动冲突解决方案
            setOnTouchListener { _, event ->
                when (event.action) {
                    android.view.MotionEvent.ACTION_DOWN -> {
                        Log.d("MineFragment", "收藏列表触摸开始")
                    }
                    android.view.MotionEvent.ACTION_MOVE -> {
                        // 直接阻止父容器拦截所有触摸事件
                        parent?.requestDisallowInterceptTouchEvent(true)
                        Log.d("MineFragment", "收藏列表触摸移动，阻止父容器拦截")
                    }
                    android.view.MotionEvent.ACTION_UP, android.view.MotionEvent.ACTION_CANCEL -> {
                        // 恢复父容器的触摸拦截
                        parent?.requestDisallowInterceptTouchEvent(false)
                        Log.d("MineFragment", "收藏列表触摸结束，恢复父容器拦截")
                    }
                }
                false // 返回false，让RecyclerView继续处理触摸事件
            }
        }
        
        // 加载收藏数据
        loadFavoriteData()
    }
    
    /**
     * 初始化离线缓存适配器，横向展示本地 offline_videos 文件夹下所有视频缩略图
     */
    private fun initOfflineCacheAdapter() {
        // 获取本地离线缓存目录
        val dir = requireContext().getExternalFilesDir(null)?.resolve("offline_videos")
        // 获取所有视频文件
        val fileList = dir?.listFiles()?.filter { it.isFile } ?: emptyList()
        // 适配器初始化
        offlineCacheAdapter = OfflineCacheAdapter(fileList)
        // 横向布局
        binding.rvMineHc.layoutManager = LinearLayoutManager(requireContext(), LinearLayoutManager.HORIZONTAL, false)
        binding.rvMineHc.adapter = offlineCacheAdapter
        // 点击播放：使用 FileProvider 获取 content uri，调用系统播放器播放本地视频
        offlineCacheAdapter.setOnItemClickListener { file ->
            // 通过 FileProvider 获取 content:// 类型的 uri，避免 FileUriExposedException
            val uri = FileProvider.getUriForFile(requireContext(), "${requireContext().packageName}.fileprovider", file)
            val intent = Intent(Intent.ACTION_VIEW)
            intent.setDataAndType(uri, "video/*")
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
            startActivity(intent)
        }
        // 长按删除：弹窗确认后删除本地文件并刷新列表
        offlineCacheAdapter.setOnItemLongClickListener { file ->
            android.app.AlertDialog.Builder(requireContext())
                .setTitle("删除缓存")
                .setMessage("确定要删除该视频吗？")
                .setPositiveButton("删除") { dialog, _ ->
                    if (file.delete()) {
                        Toast.makeText(requireContext(), "删除成功", Toast.LENGTH_SHORT).show()
                        refreshOfflineCache() // 删除后刷新列表
                    } else {
                        Toast.makeText(requireContext(), "删除失败", Toast.LENGTH_SHORT).show()
                    }
                    dialog.dismiss()
                }
                .setNegativeButton("取消", null)
                .show()
        }
    }
    
    /**
     * 刷新离线缓存列表，重新扫描本地文件夹
     */
    private fun refreshOfflineCache() {
        val dir = requireContext().getExternalFilesDir(null)?.resolve("offline_videos")
        val fileList = dir?.listFiles()?.filter { it.isFile } ?: emptyList()
        offlineCacheAdapter.updateData(fileList)
    }
    
    /**
     * 加载历史记录数据
     */
    private fun loadHistoryData() {
        lifecycleScope.launch {
            try {
                // 获取当前用户ID
                val userId = UserUtils.getCurrentUserId().ifEmpty { UserUtils.getDefaultUserId() }
                
                Log.d("MineFragment", "开始加载历史记录，用户ID: '$userId'")
                
                // 先清理重复的历史记录
                HistoryManager.cleanDuplicateHistory(userId)
                
                // 获取该用户的历史记录
                val historyList = HistoryManager.getHistoryListByUserId(userId)
                if (historyList.isNotEmpty()) {
                    historyAdapter.setData(historyList)
                    Log.d("MineFragment", "加载用户历史记录成功，用户ID: $userId, 数量: ${historyList.size}")
                } else {
                    Log.d("MineFragment", "用户暂无历史记录，用户ID: $userId")
                    historyAdapter.setData(emptyList())
                }
            } catch (e: Exception) {
                Log.e("MineFragment", "加载历史记录失败: ${e.message}", e)
                historyAdapter.setData(emptyList())
            }
        }
    }
    
    /**
     * 加载收藏数据
     */
    private fun loadFavoriteData() {
        lifecycleScope.launch {
            try {
                // 获取当前用户ID
                val userId = UserUtils.getCurrentUserId()
                
                Log.d("MineFragment", "开始加载收藏数据，用户ID: '$userId'")
                
                if (userId.isNotEmpty()) {
                    // 用户已登录，获取该用户的收藏
                    val favoriteList = FavoriteManager.getFavoriteListByUserId(userId)
                    if (favoriteList.isNotEmpty()) {
                        favoriteAdapter.setData(favoriteList)
                        Log.d("MineFragment", "加载用户收藏成功，用户ID: $userId, 数量: ${favoriteList.size}")
                    } else {
                        Log.d("MineFragment", "用户暂无收藏，用户ID: $userId")
                        favoriteAdapter.setData(emptyList())
                    }
                } else {
                    // 用户未登录，使用默认用户ID
                    val defaultUserId = UserUtils.getDefaultUserId()
                    Log.d("MineFragment", "用户未登录，使用默认用户ID: $defaultUserId")
                    
                    val favoriteList = FavoriteManager.getFavoriteListByUserId(defaultUserId)
                    if (favoriteList.isNotEmpty()) {
                        favoriteAdapter.setData(favoriteList)
                        Log.d("MineFragment", "加载默认用户收藏成功，数量: ${favoriteList.size}")
                    } else {
                        Log.d("MineFragment", "默认用户暂无收藏")
                        favoriteAdapter.setData(emptyList())
                    }
                }
            } catch (e: Exception) {
                Log.e("MineFragment", "加载收藏数据失败: ${e.message}", e)
                favoriteAdapter.setData(emptyList())
            }
        }
    }
    
    /**
     * 取消收藏
     */
    private fun unfavoriteVideo(favoriteEntity: com.bawei.lib_storage.room.entity.FavoriteEntity) {
        lifecycleScope.launch {
            try {
                val userId = UserUtils.getCurrentUserId().ifEmpty { UserUtils.getDefaultUserId() }
                val success = FavoriteManager.removeFavorite(userId, favoriteEntity.videoId)
                
                if (success) {
                    showMsg("已取消收藏")
                    // 重新加载数据
                    loadFavoriteData()
                } else {
                    showMsg("取消收藏失败")
                }
            } catch (e: Exception) {
                Log.e("MineFragment", "取消收藏失败: ${e.message}", e)
                showMsg("取消收藏失败")
            }
        }
    }
    
    /**
     * 跳转到视频详情页面
     */
    private fun navigateToVideoDetail(historyEntity: com.bawei.lib_storage.room.entity.HistoryEntity) {
        // 这里可以使用ARouter跳转到视频详情页面
        // ARouter.getInstance().build("/module_detail/DetailActivity")
        //     .withString("videoId", historyEntity.id.toString())
        //     .navigation()
        
        // 暂时显示提示
        showMsg("跳转到视频详情: ${historyEntity.title}")
    }
    
    /**
     * 跳转到视频详情页面（收藏）
     */
    private fun navigateToVideoDetail(favoriteEntity: com.bawei.lib_storage.room.entity.FavoriteEntity) {
        try {
            // 组装VideoEntity对象
            val videoEntity = com.bawei.module_detail.model.entity.VideoEntity(
                avatar_url = favoriteEntity.authorImg,
                channelid = favoriteEntity.channelId,
                commentnum = 0,
                ctime = "",
                description = favoriteEntity.content,
                group_id = "",
                id = 0,
                image_url = favoriteEntity.primaryImg,
                item_id = favoriteEntity.videoId,
                labelIds = "",
                name = favoriteEntity.authorName,
                playnum = 0,
                preview_url = favoriteEntity.primaryImg,
                publish_time = "",
                title = favoriteEntity.title,
                userid = favoriteEntity.userId,
                verifycode = "",
                videomainimag = favoriteEntity.primaryImg,
                videopath = favoriteEntity.videoPath
            )
            
            // 使用ARouter跳转到详情页
            com.alibaba.android.arouter.launcher.ARouter.getInstance()
                .build("/detail/DetailActivity")
                .withString("detail", com.google.gson.Gson().toJson(videoEntity))
                .navigation()
                
        } catch (e: Exception) {
            Log.e("MineFragment", "跳转详情页失败: ${e.message}", e)
            showMsg("跳转失败")
        }
    }
    
    /**
     * 测试滑动冲突解决方案
     */
    private fun testScrollConflictResolution() {
        try {
            // 检查观看历史RecyclerView状态
            Log.d("MineFragment", "=== 观看历史RecyclerView状态检查 ===")
            Log.d("MineFragment", "LayoutManager: ${binding.rvMineHistory.layoutManager}")
            Log.d("MineFragment", "Adapter: ${binding.rvMineHistory.adapter}")
            Log.d("MineHistory", "ItemCount: ${binding.rvMineHistory.adapter?.itemCount}")
            Log.d("MineFragment", "CanScrollHorizontally: ${binding.rvMineHistory.layoutManager?.canScrollHorizontally()}")
            Log.d("MineFragment", "Width: ${binding.rvMineHistory.width}, Height: ${binding.rvMineHistory.height}")
            
            // 检查收藏列表RecyclerView状态
            Log.d("MineFragment", "=== 收藏列表RecyclerView状态检查 ===")
            Log.d("MineFragment", "LayoutManager: ${binding.rvMineSc.layoutManager}")
            Log.d("MineFragment", "Adapter: ${binding.rvMineSc.adapter}")
            Log.d("MineFragment", "ItemCount: ${binding.rvMineSc.adapter?.itemCount}")
            Log.d("MineFragment", "CanScrollHorizontally: ${binding.rvMineSc.layoutManager?.canScrollHorizontally()}")
            Log.d("MineFragment", "Width: ${binding.rvMineSc.width}, Height: ${binding.rvMineSc.height}")
            
            // 检查父容器
            Log.d("MineFragment", "=== 父容器检查 ===")
            Log.d("MineFragment", "历史记录父容器: ${binding.rvMineHistory.parent}")
            Log.d("MineFragment", "收藏列表父容器: ${binding.rvMineSc.parent}")
            
            val message = "滑动冲突测试完成\n" +
                         "观看历史: ${binding.rvMineHistory.adapter?.itemCount ?: 0} 项\n" +
                         "收藏列表: ${binding.rvMineSc.adapter?.itemCount ?: 0} 项\n" +
                         "请查看日志获取详细信息"
            
            Toast.makeText(context, message, Toast.LENGTH_LONG).show()
            Log.d("MineFragment", "滑动冲突测试完成")
            
        } catch (e: Exception) {
            Log.e("MineFragment", "滑动冲突测试失败: ${e.message}", e)
            Toast.makeText(context, "测试失败: ${e.message}", Toast.LENGTH_SHORT).show()
        }
    }
    
    /**
     * 添加测试数据到RecyclerView
     */
    private fun addTestData() {
        try {
            // 为历史记录添加测试数据
            val testHistoryList = mutableListOf<com.bawei.lib_storage.room.entity.HistoryEntity>()
            for (i in 1..10) {
                testHistoryList.add(
                    com.bawei.lib_storage.room.entity.HistoryEntity(
                        id = i.toLong(),
                        userId = "test_user",
                        type = 1, // 1表示视频类型
                        title = "测试历史记录 $i",
                        primaryImg = "",
                        content = "这是测试历史记录内容 $i",
                        authorImg = "",
                        authorName = "测试作者 $i",
                        progress = 50, // 新增
                        lastPosition = 0L, // 新增，默认0L
                        videoId = "test_video_id_$i", // 新增，测试用
                        videopath = "" // 新增，测试用，实际应为视频播放地址
                    )
                )
            }
            historyAdapter.setData(testHistoryList)
            Log.d("MineFragment", "添加了 ${testHistoryList.size} 条测试历史记录")
            
            // 为收藏列表添加测试数据
            val testFavoriteList = mutableListOf<com.bawei.lib_storage.room.entity.FavoriteEntity>()
            for (i in 1..10) {
                testFavoriteList.add(
                    com.bawei.lib_storage.room.entity.FavoriteEntity(
                        id = i.toLong(),
                        userId = "test_user",
                        videoId = "test_video_$i",
                        title = "测试收藏 $i",
                        primaryImg = "",
                        content = "这是测试收藏内容 $i",
                        authorImg = "",
                        authorName = "测试作者 $i",
                        videoPath = "",
                        channelId = "test_channel_$i",
                        createTime = System.currentTimeMillis()
                    )
                )
            }
            favoriteAdapter.setData(testFavoriteList)
            Log.d("MineFragment", "添加了 ${testFavoriteList.size} 条测试收藏数据")
            
            Toast.makeText(context, "已添加测试数据，请尝试滑动", Toast.LENGTH_SHORT).show()
            
        } catch (e: Exception) {
            Log.e("MineFragment", "添加测试数据失败: ${e.message}", e)
            Toast.makeText(context, "添加测试数据失败: ${e.message}", Toast.LENGTH_SHORT).show()
        }
    }
    
    /**
     * 测试滑动效果
     */
    private fun testScrollEffect() {
        try {
            // 检查RecyclerView的状态
            val historyItemCount = binding.rvMineHistory.adapter?.itemCount ?: 0
            val favoriteItemCount = binding.rvMineSc.adapter?.itemCount ?: 0
            
            val message = "滑动效果测试\n" +
                         "观看历史: $historyItemCount 项 (高度: 160dp)\n" +
                         "收藏列表: $favoriteItemCount 项 (高度: 180dp)\n" +
                         "滑动方案: 简单直接\n" +
                         "请尝试水平滑动"
            
            Toast.makeText(context, message, Toast.LENGTH_LONG).show()
            Log.d("MineFragment", "滑动效果测试: $message")
            
        } catch (e: Exception) {
            Log.e("MineFragment", "测试滑动效果失败: ${e.message}", e)
            Toast.makeText(context, "测试失败: ${e.message}", Toast.LENGTH_SHORT).show()
        }
    }
    
    /**
     * 刷新用户信息UI（与个人主页风格一致）
     */
    private fun refreshUserInfo() {
        val isLogin = UserUtils.isUserLoggedIn()
        val userInfo = UserUtils.getCurrentUserInfo()
        // 用户名显示逻辑
        if (isLogin && userInfo != null) {
            binding.viewMineInfoTitleview.tvMineInfoUsername.text = "用户${userInfo.id}"
            // 按钮文案与个人主页一致
            binding.viewMineInfoTitleview.tvMineInfoMain.text = "个人主页"
        } else {
            binding.viewMineInfoTitleview.tvMineInfoUsername.text = "未登录用户"
            binding.viewMineInfoTitleview.tvMineInfoMain.text = "立即登录"
        }
        // 头像加载
        val avatarPath = AvatarUtils.getAvatarPath(requireContext(), UserUtils.getCurrentUserId())
        if (avatarPath != null) {
            Glide.with(this).load(avatarPath).circleCrop().into(binding.viewMineInfoTitleview.ivMineInfoHeaderimg)
        } else {
            Glide.with(this).load(R.drawable.logo).circleCrop().into(binding.viewMineInfoTitleview.ivMineInfoHeaderimg)
        }
    }
    
    override fun onResume() {
        super.onResume()
        Log.d("MineFragment", "onResume called")
        
        // 重新加载数据
        loadHistoryData()
        loadFavoriteData()
        
        // 刷新用户信息
        refreshUserInfo()
        
        // 检查登录状态，如果未登录则跳转到登录页面
        if (!LoginInterceptor.isLoggedIn()) {
            Log.d("MineFragment", "用户未登录，检查是否需要跳转")
            
            // 检查是否已经有登录页面在显示
            if (LoginManager.isShowingLoginPage()) {
                Log.d("MineFragment", "登录页面已显示，跳过跳转")
                return
            }
            
            Log.d("MineFragment", "尝试跳转到一键登录页面")
            val jumped = LoginInterceptor.navigateToLogin(requireContext())
            if (jumped) {
                Log.d("MineFragment", "已跳转到一键登录页面")
            } else {
                Log.d("MineFragment", "跳转失败或登录页面已显示")
            }
        } else {
            Log.d("MineFragment", "用户已登录")
        }

        // 如果有待显示的金币数，刷新UI
        pendingCoinAmount?.let {
            binding.viewMineInfoTitleview.tvMineInfoCoin.text = String.format("%.2f元", it)
            pendingCoinAmount = null
        }
    }
    
    override fun initData() {
        // 不需要额外初始化数据
    }

    override fun initEvent() {
        // 不需要额外初始化事件
    }

    override fun generateViewModel() {
        // 不需要ViewModel
    }

    override fun lazyLoad() {
        // 不需要懒加载
    }

    override fun getFragmentRootView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentMineBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }

    override fun handleState() {

    }

    private fun initAvatarPick() {
        // 权限申请
        requestPermissionLauncher = registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { result ->
            val granted = result[Manifest.permission.READ_EXTERNAL_STORAGE] == true && result[Manifest.permission.CAMERA] == true
            if (granted) {
                showAvatarPickDialog()
            } else {
                Toast.makeText(requireContext(), "请授予相机和存储权限", Toast.LENGTH_SHORT).show()
            }
        }
        // 相册选择
        pickImageLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
            if (result.resultCode == Activity.RESULT_OK) {
                val uri = result.data?.data
                uri?.let { handleImageUri(it) }
            }
        }
        // 自定义相机
        cameraLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
            if (result.resultCode == Activity.RESULT_OK) {
                val uri = result.data?.data
                uri?.let { handleImageUri(it) }
            }
        }
    }

    private fun showAvatarPickDialog() {
        val dialog = BottomSheetDialog(requireContext())
        val view = LayoutInflater.from(requireContext()).inflate(R.layout.dialog_avatar_pick, null)
        view.findViewById<TextView>(R.id.tv_pick_album).setOnClickListener {
            dialog.dismiss()
            pickFromAlbum()
        }
        view.findViewById<TextView>(R.id.tv_pick_camera).setOnClickListener {
            dialog.dismiss()
            // 启动自定义相机Activity
            cameraLauncher.launch(Intent(requireContext(), CameraActivity::class.java))
        }
        view.findViewById<TextView>(R.id.tv_cancel).setOnClickListener { dialog.dismiss() }
        dialog.setContentView(view)
        dialog.show()
    }

    private fun pickFromAlbum() {
        val intent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
        pickImageLauncher.launch(intent)
    }

    private fun handleImageUri(uri: Uri) {
        try {
            val bitmap = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                val source = ImageDecoder.createSource(requireContext().contentResolver, uri)
                // Force software bitmap to prevent "Software rendering doesn't support hardware bitmaps"
                ImageDecoder.decodeBitmap(source) { decoder, _, _ ->
                    decoder.allocator = ImageDecoder.ALLOCATOR_SOFTWARE
                }
            } else {
                MediaStore.Images.Media.getBitmap(requireContext().contentResolver, uri)
            }
            // 保存为当前用户头像
            val userId = UserUtils.getCurrentUserId()
            AvatarUtils.saveAvatar(requireContext(), userId, bitmap)
            // 显示圆形头像
            Glide.with(this).load(bitmap).circleCrop().into(binding.viewMineInfoTitleview.ivMineInfoHeaderimg)
        } catch (e: IOException) {
            e.printStackTrace()
            Toast.makeText(requireContext(), "头像设置失败", Toast.LENGTH_SHORT).show()
        }
    }

    /**
     * 外部调用：更新金币金额显示
     */
    fun updateCoin(amount: Double) {
        // binding是否已初始化（Fragment已attach且View已创建）
        if (view != null && isAdded) {
            binding.viewMineInfoTitleview.tvMineInfoCoin.text = String.format("%.2f元", amount)
            pendingCoinAmount = null
        } else {
            pendingCoinAmount = amount
        }
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        // 如果有待显示的金币数，刷新UI
        pendingCoinAmount?.let {
            binding.viewMineInfoTitleview.tvMineInfoCoin.text = String.format("%.2f元", it)
            pendingCoinAmount = null
        }
    }
}